package com.jframe.sso.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jframe.sso.model.CurUser;
import com.jframe.sso.model.Role;
import com.jframe.sso.model.User;
import com.jframe.sso.model.UserGroup;
import com.jframe.sso.service.RoleService;
import com.jframe.sso.service.UserGroupService;
import com.jframe.sso.service.UserService;
import com.jframe.sys.controller.ExtendAction;
import com.jframe.sys.controller.utils.BaseAction;
import com.jframe.sys.controller.utils.DicCache;
import com.jframe.sys.controller.utils.JsBuilder;
import com.jframe.sys.controller.utils.QueryHelp;
import com.jframe.sys.controller.utils.TabmCache;
import com.jframe.sys.orm.utils.ResultSet;
import com.jframe.sys.utils.CalendarUtil;
import com.jframe.sys.utils.JsonUtil;
import com.jframe.sys.utils.SpringUtil;
import com.jframe.sys.utils.StringUtil;
import com.jframe.sys.webui.Columns;
import com.jframe.sys.webui.Editor;
import com.jframe.sys.webui.Grid;
import com.jframe.sys.webui.Tab;
import com.jframe.sys.webui.Tree;


public class UserAction extends ExtendAction{
	
	private static String ACTION="userAction";
	private static String SERVICE="userService";
	private static Class<User> CLAZZ=User.class;
	
	public void list(){
		//加载数据字典
		List<Columns> frozenColumns = new ArrayList<Columns>();//固定列
		List<Columns> commonColumns = new ArrayList<Columns>();
		frozenColumns.add(new Columns("ck","",40,""));
		frozenColumns.add(new Columns("id", "编号", 80,""));
		frozenColumns.add(new Columns("userNo", "账号", 100,""));
		commonColumns.add(new Columns("userName","用户名",120,""));
		commonColumns.add(new Columns("roleName","角色",120,""));
		//commonColumns.add(new Columns("roleId","角色",120,new Editor("combotree",true),TabmCache.getCombotreeJson("sm_sys_role")));
		commonColumns.add(new Columns("tel","联系方式",120,""));
		commonColumns.add(new Columns("email","email",120,""));
		commonColumns.add(new Columns("skin","皮肤",120,""));
		//commonColumns.add(new Columns("deptId","部门",120,""));
		//commonColumns.add(new Columns("memberId","成员",120,""));
		commonColumns.add(new Columns("active","有效否",100,new Editor("combobox",true),DicCache.getComboboxJson("dm_sys_active")));
		Grid grid = new Grid();
		grid.setUrl(this.getUrl(ACTION+".do?method=load"));
		String js = JsBuilder.getJsStr(frozenColumns, commonColumns, grid);
		this.request.setAttribute("js", js);
		this.forward("/jframe/sso/list/userList.jsp");
	}

	public void load(){
		int tabId = StringUtil.parseInt(this.pageInfo.getPageTabId(request));
		RoleService roleService = (RoleService)this.getBean("roleService");
		List<Role> rolels =  roleService.find("from Role where groupId=? and active=? ", new Object[]{tabId,1});
		this.baseLoad(SERVICE, CLAZZ, " and roleId in ("+this.getRoleIds(rolels)+")","");
	}
	
	public void save(){
		this.baseSave(SERVICE, CLAZZ);
	}
	
	public Object beforeSave(Object obj){
		String type = this.request.getParameter("type");
		RoleService roleService = (RoleService)SpringUtil.getBean("roleService");
		User user = (User) obj;
		Role role = roleService.load(user.getRoleId());
		user.setRoleName(role.getName());
		UserService userService = (UserService)this.getBean("userService");			
		if(type.equals("edit")){
			CurUser curUser = (CurUser)session.getAttribute("curUser");
			User userTemp = userService.load(user.getId());
			user.setId(userTemp.getId());
			user.setPwd(userTemp.getPwd());
			if(curUser.getUserNo().equals(user.getUserNo())){				
				curUser.setUserId(user.getId());
				curUser.setUserNo(user.getUserNo());
				curUser.setUserName(user.getUserName());
				curUser.setRoleId(user.getRoleId());			
				curUser.setIp(this.getIpAddr());
				curUser.setRoleName(role.getName());
				curUser.setLoginTime(CalendarUtil.getDateTime());
				curUser.setDeptId(user.getDeptId());
				curUser.setMemberId(user.getMemberId());
				curUser.setSkin(user.getSkin());
				session.setAttribute("curUser", curUser);
			}
		}else{
			user.setPwd(StringUtil.encrypt(user.getPwd()));
		}
		return user;
	}
	
	public void delete(){
		this.baseDelete(SERVICE);
	}
	
	public void changepwd(){
		Map<String,Object> map = new HashMap<String,Object>();
		String objstr = this.request.getParameter("obj");
		User user  = (User) JsonUtil.json2Obj(objstr,CLAZZ);
		String pwd =user.getPwd();
		UserService userService = (UserService)this.getBean("userService");	
		user = userService.load(user.getId());
		user.setPwd(StringUtil.encrypt(pwd));
		userService.save(user);
		map.put("result", true);
		map.put("obj", user);
		this.print(JsonUtil.map2Json(map));
	}
	
	private String getRoleIds(List<Role> rolels){
		String ids = "";
		for(Role role:rolels){
			ids +=role.getId()+",";
		}
		if(ids.length()>0){
			ids=ids.substring(0, ids.length()-1);
		}
		return ids;
	}
	
	public void getRole(){
		int groupId = StringUtil.parseInt(this.request.getParameter("groupId"));
		RoleService roleService = (RoleService)this.getBean("roleService");
		List<Role> rolels =  roleService.find("from Role where groupId=? and active=? order by id", new Object[]{groupId,1});
		String json = "[";
		for(Role role:rolels){
			json +="{'id':"+role.getId()+",";
			json +="'name':'"+role.getName()+"'},";		
		}
		//去除尾部逗号		
		if(rolels.size()>0){
			json = json.substring(0,json.length()-1);
		}	
		json += "]";
		this.print(json);
	}
	
	public List<UserGroup> getUserGroups(){
		UserGroupService userGroupService = (UserGroupService)this.getBean("userGroupService");
		List<UserGroup> ls = userGroupService.findList("where active=1 order by id");
		return ls;
	}
	
	public void getRightTrees(){
		List<Map<String,Object>> items = new ArrayList<Map<String,Object>>();	
		int groupId = StringUtil.parseInt(this.request.getParameter("groupId"));
		RoleService roleService = (RoleService)SpringUtil.getBean("roleService");
		List<Role> treels = roleService.findByGroupId(groupId);
		for(Role role:treels){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("id", role.getId());
			map.put("name", role.getName());
			map.put("pId",role.getUpId());
			items.add(map);
		}
		this.print(JsonUtil.list2Json(items));
	}
	
	public void getObjById(){
		this.print(JsonUtil.obj2Json(this.getObject(SERVICE)));
	}
	
	public void getUserInfo(){
		User user = (User)this.getObject(SERVICE);
		user.setPwd(""); //清空密码，防止泄露。
		this.print(JsonUtil.obj2Json(user));
	}
	
	public void textThread(String[] args){
		System.out.println(CalendarUtil.getDateTime()+"任务线程启动了！");
	}
	
	public void goUserInfo(){
		this.forward("/jframe/sso/edit/personInfoEdit.jsp");
	}
}
